package com.auxgroup.hr.front.site.co.personnel;

import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import com.auxgroup.hr.front.commons.Constant;
import com.auxgroup.hr.front.dao.domain.*;
import com.auxgroup.hr.front.dao.repository.PsFpSalaryExpTRepository;
import com.auxgroup.hr.front.service.personnal.*;
import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.vo.BaseResponseVO;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dozer.IObjectMapper;
import com.auxgroup.hr.front.site.co.BaseCO;
import com.auxgroup.hr.front.site.vo.person.LeavebalRespVO;
import com.auxgroup.hr.front.site.vo.person.PaySlipReqVO;
import com.auxgroup.hr.front.site.vo.person.PaySlipRespVO;
import com.auxgroup.hr.front.site.vo.person.PersonBaseInfoVO;
import com.auxgroup.hr.front.site.vo.person.PersonPyCompRespVO;

/**
 * 基本信息
 *
 * @author wangchangyun
 * @version 创建时间：180523
 */
@RestController
@RequestMapping("${auxgroup.hr.contextPath}/personalData")
public class PersonalDataCO extends BaseCO {

    private static final Logger logger = LoggerFactory.getLogger(PersonalDataCO.class);

    @Autowired
    public PersonalDataService personalDataService;

    @Autowired
    public EmplPhotoService emplPhotoService;

    @Autowired
    public JobCurrService jobCurrService;

    @Autowired
    private JobService jobService;
    @Autowired
    private ContractDataService contractDataService;


    @Resource(name = "dozerMapper")
    protected IObjectMapper objectMapper;

    @Autowired
    private PsFpSalaryExpTRepository psFpSalaryExpTRepository;

    /**
     * 我的信息 主页内容获取
     *
     * @param emplid
     * @return
     */
    @GetMapping(value = "/getBaseInfo")
    public BaseResponseVO getBaseInfo(String emplid) {
        logger.info("get person base info request:{}", emplid);
        //个人信息获取
        PsCPersonalData personalData = personalDataService.getPersonalData(emplid);
        if (personalData == null) {
            return buildRespone(BaseRetCode.CODE_ERROR_PERSONDATA_NOT_EXIST);
        }
        //拷贝个人信息
        PersonBaseInfoVO baseInfovo = objectMapper.map(personalData, PersonBaseInfoVO.class);
        JobCurrPrimary primary = new JobCurrPrimary(new BigDecimal(0), emplid);
        PsCJobCurrVw job = jobCurrService.getDefaultJobCurr(primary);//职称获取
        if (job != null) {
            objectMapper.map(job, baseInfovo);
        }
        EmplPhotoPrimary photoPri = new EmplPhotoPrimary(emplid, "PAGE");
        PsEmplPhoto photo = emplPhotoService.getEmplPhoto(photoPri);//头像查询
        if (photo != null) {
            String jpgUrl = emplPhotoService.buildEmplPhoto(photo);//头像处理
            objectMapper.map(photo, baseInfovo);//拷贝照片信息
            baseInfovo.setPhotoUrl(jpgUrl);
        }
        return buildRespone(baseInfovo);
    }

    @GetMapping(value = "/getNationalId")
    public BaseResponseVO getNationalId(@SessionGain("user") UserDTO user) {
        logger.info("get nation id request:{}", user.getEmplId());
        //个人信息获取
        PsCPersonalData personalData = personalDataService.getPersonalData(user.getEmplId());
        if (personalData == null) {
            return buildRespone(BaseRetCode.CODE_ERROR_PERSONDATA_NOT_EXIST);
        }

        return buildRespone(personalData.getNationalId());
    }


    @PostMapping(value = "/loginPayroll")
    public BaseResponseVO loginPayroll(@SessionGain("user") UserDTO user, String password) {
        //个人信息获取
        boolean login = personalDataService.loginPayroll(user.getEmplId(), password);
        if (login) {
            return new BaseResponseVO(BaseRetCode.CODE_SUCCESS, "登陆成功");
        } else {
            return new BaseResponseVO(BaseRetCode.CODE_ERROR_LOGIN_PAYROLL, "登陆失败");
        }
    }

    /**
     * 个人信息详细信息的基本信息展示
     *
     * @param emplid
     * @return
     */
    @GetMapping(value = "/getOneDetail")
    public BaseResponseVO getOneDetail(String emplid) {
        logger.info("getPersonalData param= {}", emplid);
        if (StringUtils.isBlank(emplid)) {
            return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(), "人员ID不能为空");
        }
        PsCPersonalData personalData = personalDataService.getPersonalData(emplid);

        //导师姓名
        if (StringUtils.isNotEmpty(personalData.getcEmplId())) {
            PsCPersonalData user = personalDataService.getPersonalData(personalData.getcEmplId());
            if (user != null) {
                personalData.setcEmplName(user.getName());
            }
        }
        //岗位短号
        personalData.setJobCodeNum(jobService.getPostShortNbr(emplid));

        List<Object[]> objs = sysDictService.getObjectListFromSql(Constant.HIRE_DATE_QUERY, new String[]{emplid});
        if (objs != null && !objs.isEmpty()) {
            Object[] obj = objs.get(0);
            //首次入职
            personalData.setFirstInCompanyDt((Date) obj[0]);
            personalData.setRsWklifBgnDt((Date) obj[1]);
            //转正日期
            personalData.setZhuanzhengDt((Date) obj[2]);
        } else {
            personalData.setRsWklifBgnDt(null);
        }


        return buildRespone(personalData);
    }

    /**
     * 个人信息详细信息的基本信息展示
     *
     * @param emplid
     * @return
     */
    @GetMapping(value = "/getOne")
    public BaseResponseVO getOne(String emplid) {
        logger.info("getPersonalData param= {}", emplid);
        if (StringUtils.isBlank(emplid)) {
            return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(), "人员ID不能为空");
        }
        PsCPersonalData personalData = personalDataService.getPersonalData(emplid);
        return buildRespone(personalData);
    }

    /**
     * 获取下属薪酬信息
     *
     * @param emplid
     * @return
     */
    @GetMapping(value = "/getPyComp")
    public BaseResponseVO getPyComp(String emplid, @SessionGain("user") UserDTO user) {
        if (StringUtils.isBlank(emplid)) {
            return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(), "人员ID不能为空");
        }
        if (!StringUtils.equals(user.getEmplId(), emplid) && !personalDataService.hasPaySlipPermission(user.getOprId())) {
            return new BaseResponseVO(BaseRetCode.CODE_ERROR_AUTH_UNAUTH, "没有查看权限");
        }
        PsCPyCompVw pyComp = personalDataService.getPyComp(emplid);
        if (pyComp == null) {
            return buildRespone(BaseRetCode.CODE_ERROR_PY_COMP_NOT_EXIST);
        }
        PersonPyCompRespVO respVO = objectMapper.map(pyComp, PersonPyCompRespVO.class);
//		respVO.setPyMods(personalDataService.getPyMods(emplid));
        buildPyComps(respVO, pyComp);
        return buildRespone(respVO);
    }

    /**
     * 构建薪酬描述信息
     *
     * @param respVO
     * @param pyComp
     */
    private void buildPyComps(PersonPyCompRespVO respVO, PsCPyCompVw pyComp) {
        Map<String, Object> comp;
        List<Map<String, Object>> pycomps = new ArrayList<Map<String, Object>>();
        //月固薪
        if (pyComp.getcComprate1() != null && pyComp.getcComprate1().compareTo(new BigDecimal(0)) > 0) {
            comp = new HashMap<String, Object>();
            comp.put("name", "月薪");
            comp.put("value", pyComp.getcComprate1());
            pycomps.add(comp);
        }
        //基本工资
        if (pyComp.getcComprate2() != null && pyComp.getcComprate2().compareTo(new BigDecimal(0)) > 0) {
            comp = new HashMap<String, Object>();
            comp.put("name", "年终奖基数");
            comp.put("value", pyComp.getcComprate2());
            pycomps.add(comp);
        }
        //岗位工资
        if (pyComp.getcComprate3() != null && pyComp.getcComprate3().compareTo(new BigDecimal(0)) > 0) {
            comp = new HashMap<String, Object>();
            comp.put("name", "年收标准");
            comp.put("value", pyComp.getcComprate3());
            pycomps.add(comp);
        }
        //加班工资
        if (pyComp.getcComprate4() != null && pyComp.getcComprate4().compareTo(new BigDecimal(0)) > 0) {
            comp = new HashMap<String, Object>();
            comp.put("name", "日薪标准");
            comp.put("value", pyComp.getcComprate4());
            pycomps.add(comp);
        }
        //绩效工资
        if (pyComp.getcComprate5() != null && pyComp.getcComprate5().compareTo(new BigDecimal(0)) > 0) {
            comp = new HashMap<String, Object>();
            comp.put("name", "时薪标准");
            comp.put("value", pyComp.getcComprate5());
            pycomps.add(comp);
        }
        respVO.setPycomps(pycomps);
    }

    /**
     * 查询假期剩余
     *
     * @param emplid
     * @return
     */
    @GetMapping(value = "/getLeaveBalInfo")
    public BaseResponseVO getLeavebalInfo(String emplid) {
        if (StringUtils.isBlank(emplid)) {
            return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(), "人员ID不能为空");
        }
        Map<String, String> leave = personalDataService.getLeavebalInfo(emplid);
        if (leave != null) {
            LeavebalRespVO respVO = new LeavebalRespVO();
            respVO.setAdjDays(leave.get("C_ADJ_BAL"));
            respVO.setAdjDisplay(leave.get("C_ADJ_VISIBLE"));
            respVO.setAnnDays(leave.get("C_ANN_BAL"));
            respVO.setAnnDisplay(leave.get("C_ANN_VISIBLE"));
            return buildRespone(respVO, false);
        }
        return buildRespone(BaseRetCode.CODE_ERROR_GET_LEAVELAB_INFO_FAIL);
    }


    /**
     * 获取个人薪酬信息
     *
     * @param reqVO
     * @param user
     * @return
     */
    @GetMapping(value = "/getPaySlip")
    public BaseResponseVO getPaySlip(PaySlipReqVO reqVO, @SessionGain("user") UserDTO user) {
        if (StringUtils.isBlank(reqVO.getYear())) {
            return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(), "年份不能为空");
        }
        if (StringUtils.isBlank(reqVO.getEmplid())) {
            reqVO.setEmplid(user.getEmplId());
        } else {
            if (!personalDataService.hasPaySlipPermission(user.getOprId())) {
                return new BaseResponseVO(BaseRetCode.CODE_ERROR_AUTH_UNAUTH, "没有查看权限");
            }
        }
        List<PsCPayslipHdr> paySlips = personalDataService.getPaySlip(reqVO.getEmplid(), reqVO.getYear(), reqVO.getCalRunId());
        List<PaySlipRespVO> respVos = new ArrayList<PaySlipRespVO>();
        if (paySlips != null && !paySlips.isEmpty()) {
            for (PsCPayslipHdr paySlip : paySlips) {

                PaySlipRespVO respVo = objectMapper.map(paySlip, PaySlipRespVO.class);
                respVo.setPaySlips(personalDataService.buildSlips(paySlip));
                respVos.add(respVo);
            }
        }
        return buildRespone(respVos, false);
    }


}
